package com.sensePlusVR.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sensePlusVR.activity.user.LoginActivity;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.utils.AppManager;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.FileUtils;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.PageJumpUtil;
import com.sensePlusVR.widget.WaterRippleHelper;
import com.sensePlusVR.widget.WaterRippleView;
import com.senseplusvr.sdk.videoview.HemiGLView;
import com.senseplusvr.sdk.videoview.SvrInterf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("InflateParams")
public class VrRealTestBaseActivity extends AppCompatActivity implements
		SvrInterf.SurfaceTexCallback {

	private static final String TAG = VrRealTestBaseActivity.class.getSimpleName();

	private String[] gameConfigs;

	private boolean mIsVrMode;
	private boolean mIsVrVideo;
	private boolean mIsFromSetting;
	private HemiGLView hemiGlView;

	private final String mVrVideo="test_vr.stream";
	private final String m2dVideo="test_2d.stream";
	//private final String mVrconfig="test_vr.json";
	//private final String m2dconfig="test_2d.json";
	private String vrFile;
	//private String vrConfig;
	private String d2File;
	//private String d2Config;
	
	private WaterRippleHelper helper;
	
	private RelativeLayout detect_root_relative;
	
	private RelativeLayout decoder_vr_result_relative;
	private RelativeLayout decoder_vr_fps_relative;
	private RelativeLayout gpu_vr_fps_relative;
	private RelativeLayout gpu_vr2d_fps_relative;
	
	
	private TextView accel_sensor_tv;
	private TextView grav_sensor_tv;
	private TextView gyro_sensor_tv;
	private TextView decoder_vr_result_tv;
	private TextView decoder_vr_fps_tv;
	private TextView gpu_vr_fps_tv;
	private TextView gpu_vr2d_fps_tv;
	
	private TextView detect_result_tv;
	private Button detect_enter_btn;
	
	public VRApplication vrApplication;
	
	private Timer mTimer;
	private MyTimerTask myTimerTask;
	
	private Map<String, String> mapStrings;
	
	private boolean canBack = false;
	
	
	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		MyLog.e(TAG, "create test active");
		initDataFromIntent();
		if(mIsVrMode){
			setContentView(R.layout.activity_test_real_game_land);	
		}else{
			setContentView(R.layout.activity_test_real_game);
		}
			
			hemiGlView = (HemiGLView) findViewById(R.id.hemiGlView);

			hemiGlView.setSurfaceTexCallback(this);

			hemiGlView.setFocusable(true);

			hemiGlView.setFocusableInTouchMode(true);
			hemiGlView.pauseTracking();
			hemiGlView.setGyroDataEnable(false);
			
			MyLog.e(TAG, "cp asssets");
			vrFile = copyTestFile(mVrVideo);
			d2File = copyTestFile(m2dVideo);
			
			initDetectView();
		
	}
	
	
	
	private void initDetectView() {
		
		AppManager.getInstance().addActivity(this);
		vrApplication = VRApplication.getInstance();
		mapStrings = new HashMap<String, String>();
		
		detect_root_relative = (RelativeLayout) findViewById(R.id.detect_root_relative);
		
		decoder_vr_result_relative = (RelativeLayout) findViewById(R.id.decoder_vr_result_relative);
		decoder_vr_fps_relative = (RelativeLayout) findViewById(R.id.decoder_vr_fps_relative);
		gpu_vr_fps_relative = (RelativeLayout) findViewById(R.id.gpu_vr_fps_relative);
		gpu_vr2d_fps_relative = (RelativeLayout) findViewById(R.id.gpu_vr2d_fps_relative);
		
		accel_sensor_tv = (TextView) findViewById(R.id.accel_sensor_tv);
		grav_sensor_tv = (TextView) findViewById(R.id.grav_sensor_tv);
		gyro_sensor_tv = (TextView) findViewById(R.id.gyro_sensor_tv);
		decoder_vr_result_tv = (TextView) findViewById(R.id.decoder_vr_result_tv);
		decoder_vr_fps_tv = (TextView) findViewById(R.id.decoder_vr_fps_tv);
		gpu_vr_fps_tv = (TextView) findViewById(R.id.gpu_vr_fps_tv);
		gpu_vr2d_fps_tv = (TextView) findViewById(R.id.gpu_vr2d_fps_tv);
		detect_result_tv = (TextView) findViewById(R.id.detect_result_tv);
		detect_enter_btn = (Button) findViewById(R.id.detect_enter_btn);
		
		if(mIsFromSetting){
			detect_enter_btn.setText(getResources().getString(R.string.confirm));
		}else{
			detect_enter_btn.setText(getResources().getString(R.string.enter));
		}
		
		detect_enter_btn.setOnClickListener(myOnclickListener);
		
		mTimer = new Timer();

		helper = new WaterRippleHelper(
					VrRealTestBaseActivity.this,detect_root_relative);
		 //先让水波进行到60%
			if(mIsVrMode){
				helper.showEvent(0,60, 100,false,false);
			}else{
				helper.showEvent(0,60, 100,true,true);
			}
			
			helper.startAnim();
		
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//强制升级屏蔽返回键
		 if(keyCode==KeyEvent.KEYCODE_BACK){
			 if(canBack){
					if(mIsFromSetting){
						AppManager.getInstance().finishActivity();
					}else{
						AppManager.getInstance().finishAllActivity();	
					}
					 return super.onKeyDown(keyCode, event);
				}
		 } 
		 return true;
	}
	
	
	private OnClickListener myOnclickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.detect_enter_btn:
				//当真正获取到手机性能后再存储此标志，否则下次继续进入检测手机性能
				MySharedPreferences.save2(VrRealTestBaseActivity.this,
						MySharedPreferences.NAME_NOT_CLEAR,Constant.IS_FIRST_INSTANT, true);
				if(mIsFromSetting){
					AppManager.getInstance().finishActivity();
				}else{
					startActivity(new Intent(VrRealTestBaseActivity.this, LoginActivity.class));
					AppManager.getInstance().finishAllActivity();	
				}
				break;

			}
		}
	};
	
	public void moveView(Map<String, String> mapStrings){
		this.mapStrings = mapStrings;
		helper.showEvent(60,100, 100,true,false);
		if (mTimer != null) {
			if (myTimerTask != null) {
				myTimerTask.cancel(); // 将原任务从队列中移除
			}
			myTimerTask = new MyTimerTask();

			mTimer.schedule(myTimerTask, WaterRippleView.DEFAULT_DURATION * 60/100);


		}
	}
	
	class MyTimerTask extends TimerTask {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {
				public void run() {

					if (!mIsVrMode) {
						
						canBack = true;
						
						setDetectResult(mapStrings);
						
						if(helper == null)return;
						helper.moveView();

					}

				}
			});

		}

	}
	
	
	public void setDetectResult(Map<String,String> mapStrings){
		
		String hasAccel = mapStrings.get(getResources().getString(R.string.has_accel_sensor));
		String hasGrav = mapStrings.get(getResources().getString(R.string.has_grav_sensor));
		String hasGyro = mapStrings.get(getResources().getString(R.string.has_gyro_sensor));
		String decoderVRResult = mapStrings.get(getResources().getString(R.string.decoder_vr_result));
		String decoderVRFps = mapStrings.get(getResources().getString(R.string.decoder_vr_fps));
		String gpuVRFps = mapStrings.get(getResources().getString(R.string.gpu_vr_fps));
		String gpuVR2DFps = mapStrings.get(getResources().getString(R.string.gpu_vr2d_fps));
		
		
		boolean hasAccelB = Boolean.parseBoolean(hasAccel);
		boolean hasGravB = Boolean.parseBoolean(hasGrav);
		boolean hasGyroB = Boolean.parseBoolean(hasGyro);
		boolean decoderVRResultB = Boolean.parseBoolean(decoderVRResult);
		int decoderVRFpsI = Integer.parseInt(decoderVRFps);
		int gpuVRFpsI = Integer.parseInt(gpuVRFps);
		int gpuVR2DFpsI = Integer.parseInt(gpuVR2DFps);
		
		accel_sensor_tv.setText(hasAccelB==true?"Yes":"No");
		grav_sensor_tv.setText(hasGravB==true?"Yes":"No");
		gyro_sensor_tv.setText(hasGyroB==true?"Yes":"No");
		decoder_vr_result_tv.setText(decoderVRResultB==true?"Yes":"No");
		decoder_vr_fps_tv.setText(decoderVRFps);
		gpu_vr_fps_tv.setText(gpuVRFps);
		gpu_vr2d_fps_tv.setText(gpuVR2DFps);
		
		//如果三个传感器有一个没有则隐藏decoder_vr_result_tv
		if(!hasAccelB || !hasGravB || !hasGyroB){
			decoder_vr_result_relative.setVisibility(View.INVISIBLE);
			decoder_vr_fps_relative.setVisibility(View.INVISIBLE);
			gpu_vr_fps_relative.setVisibility(View.INVISIBLE);
			gpu_vr2d_fps_relative.setVisibility(View.INVISIBLE);
		}
		
		//如果 Decoder VR fps=0，Decoder VR video变成NO
		if(decoderVRFpsI <= 0){
			decoder_vr_result_tv.setText("No");
		}
		
		//如果decoder_vr_fps_tv,gpu_vr_fps_tv,gpu_vr2d_fps_tv任意一个为零Decoder VR fps，GPU VR render fps，GPU 2D render fps不要显示
		if(!decoderVRResultB || decoderVRFpsI <= 0){
			decoder_vr_fps_relative.setVisibility(View.INVISIBLE);
			gpu_vr_fps_relative.setVisibility(View.INVISIBLE);
			gpu_vr2d_fps_relative.setVisibility(View.INVISIBLE);
		}
		
		if (!hasAccelB&&!hasGravB&&!hasGyroB) {
			detect_result_tv.setText(R.string.sensor_not_accel_gravity_gyro_tip);
			return;
		}

		if (!hasAccelB&&!hasGravB) {
			detect_result_tv.setText(R.string.sensor_not_accel_gravity_tip);
			return;
		}

		if (!hasAccelB&&!hasGyroB) {
			detect_result_tv.setText(R.string.sensor_not_accel_gyro_tip);
			return;
		}

		if (!hasGravB&&!hasGyroB) {
			detect_result_tv.setText(R.string.sensor_not_gravity_gyro_tip);
			return;
		}
		
		if(!hasAccelB){
			detect_result_tv.setText(R.string.sensor_not_accel_tip);
			return;
		}
		if(!hasGravB){
			detect_result_tv.setText(R.string.sensor_not_gravity_tip);
			return;
		}
		if(!hasGyroB){
			detect_result_tv.setText(R.string.sensor_not_gyro_tip);
			return;
		}
		if(!decoderVRResultB){
			detect_result_tv.setText(R.string.decoder_vr_video_not);
			return;
		}
		
		if(decoderVRFpsI <= 0 || gpuVRFpsI <= 0 || gpuVR2DFpsI <= 0){
			detect_result_tv.setText(R.string.decoder_or_gpu_0);
			return;
		}
		
		if(decoderVRFpsI < 60){
			detect_result_tv.setText(R.string.decoder_vr_fps_less_60);
			return;
		}
		if(gpuVRFpsI < 50 && gpuVR2DFpsI < 50){
			detect_result_tv.setText(R.string.gpu_2d_render_fps_less_50);
			return;
		}
		if(decoderVRFpsI >= 60 && gpuVRFpsI < 50 && gpuVR2DFpsI >= 50){
			detect_result_tv.setText(R.string.gpu_2d_render_fps_more_50);
			return;
		}
		if(decoderVRFpsI >= 60 && gpuVRFpsI >= 50){
			detect_result_tv.setText(R.string.sensor_all_have_tip);
			return;
		}
	}
	
	@Override
	public void finish() {
		super.finish();
	}
	
	public String getActions(){
		return String.format("V3:%s,%s", "test", mIsVrVideo?vrFile:d2File);
	}
	
	public boolean getVrVideo(){
		return mIsVrVideo;
	}

	private String copyTestFile(String fileName){
		String path = FileUtils.getExternalCacheDir(VRApplication.getAppContext());
		String toFile = path+File.separator+fileName;
		InputStream in = null;
		FileOutputStream out = null;
		try {
			in = getAssets().open(fileName);
			File ofile = new File(toFile);
			if (ofile.exists()){
				MyLog.e(TAG, "file "+toFile+" is exist");
				return toFile;
			}
			out = new FileOutputStream(ofile);
			byte[] buf = new byte[8192];
			int len = 0;
		    while ((len = in.read(buf)) > 0) {
                  out.write(buf, 0, len);
            }
		    out.close();
		    in.close();
		    MyLog.d(TAG, "copy assets file "+fileName+" ok");
		    return toFile;
		}catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			MyLog.e(TAG, "open assset exception");
		}
		return null;
	}

	private void initDataFromIntent() {

		Bundle bundle = getIntent().getExtras();

		//TODO VRMode_KEY = true,false
		mIsVrMode = bundle.getBoolean(PageJumpUtil.VRMode_KEY, true);
		mIsVrVideo = bundle.getBoolean(PageJumpUtil.VRVideo_KEY, true);
		mIsFromSetting = bundle.getBoolean(PageJumpUtil.FROMSETTING_KEY,false);
		
		MyLog.d(TAG, "mIsFromSetting : " + mIsFromSetting);

		if (mIsVrMode) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		} else {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
		
	}
	
	
	/**
	 * 返回配置路径
	 * 
	 * @return
	 */
	public String[] getGameConfig() {

		return gameConfigs;
	}

	/**
	 * 是否vr模式
	 * 
	 * @return
	 */
	public boolean getVrMode() {

		return mIsVrMode;
	}
	
	public boolean getIsFromSetting(){
		
		return mIsFromSetting;
		
	}

	/**
	 * 返回hemiGlView
	 * 
	 * @return
	 */
	public HemiGLView getHemiGlView() {

		return hemiGlView;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	public void onSurfaceTexture(SurfaceTexture surfacetexture) {
		MyLog.d(TAG, "onSurfaceTexture...");
		// 设置vr模式
		hemiGlView.setVrMode(mIsVrMode);
	}

}
